/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BuscarContenidoInicio.java
 *
 * Created on 26-feb-2012, 21:13:31
 */

package proy1sistdistribuidos.interfaz;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import proy1sistdistribuidos.control.advertisements.AdvertisementContenidoFisicoImpl;
import proy1sistdistribuidos.control.advertisements.AdvertisementImagenImpl;
import proy1sistdistribuidos.modelo.ControladorProySistDistribuidos;
import proy1sistdistribuidos.modelo.TiposMime;
import sun.misc.BASE64Decoder;

/**
 *
 * @author Juan Felipe Garcia, Carlos Diaz Maya
 */
public class BuscarContenidoInicio extends javax.swing.JFrame implements Observer {

    private ControladorProySistDistribuidos controlador;
    private HashMap<Integer , String[]> personas  = new HashMap<Integer, String[]>();
    private DefaultListModel model = new DefaultListModel();
    private PTableModel modeloTabla;
    private HashMap<String, AdvertisementImagenImpl> results = new HashMap<String, AdvertisementImagenImpl>();
    private String etiquetaSeleccionada;

    /** Creates new form BuscarContenidoInicio */
    public BuscarContenidoInicio() {

        initComponents();
        componenteListaPersonas.setModel(model);
    }

    public BuscarContenidoInicio(ControladorProySistDistribuidos control) {
        this.controlador = control;
        inicializarColumnasTabla();
        initComponents();
       
    }

     public void inicializarColumnasTabla() {
        ArrayList columnas = new ArrayList();
        columnas.add("Etiqueta");
        columnas.add("Fecha de creación");
        columnas.add("Nombres de personas");
        this.modeloTabla = new PTableModel(columnas);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        componenteListaPersonas = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jtextNombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jtextApellido = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(proy1sistdistribuidos.interfaz.Principal.class).getContext().getResourceMap(BuscarContenidoInicio.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        componenteListaPersonas.setModel(model);
        componenteListaPersonas.setName("componenteListaPersonas"); // NOI18N
        jScrollPane1.setViewportView(componenteListaPersonas);

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jtextNombre.setText(resourceMap.getString("jtextNombre.text")); // NOI18N
        jtextNombre.setName("jtextNombre"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jtextApellido.setText(resourceMap.getString("jtextApellido.text")); // NOI18N
        jtextApellido.setName("jtextApellido"); // NOI18N

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jTable1.setModel(modeloTabla);
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane3.setViewportView(jTable1);

        jScrollPane2.setViewportView(jScrollPane3);

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText(resourceMap.getString("jButton5.text")); // NOI18N
        jButton5.setName("jButton5"); // NOI18N
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 304, Short.MAX_VALUE)
                .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37))
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtextNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtextApellido))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(114, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(201, 201, 201)
                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(219, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtextNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jtextApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(14, 14, 14)
                .addComponent(jButton5)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        int i = componenteListaPersonas.getModel().getSize();
        ((DefaultListModel) componenteListaPersonas.getModel()).add(i, jtextNombre.getText()+" "+jtextApellido.getText());
        personas.put(i, new String[]{jtextNombre.getText(),jtextApellido.getText()});
        jtextNombre.setText("");
        jtextApellido.setText("");
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        int i = componenteListaPersonas.getSelectedIndex();
        ((DefaultListModel) componenteListaPersonas.getModel()).remove(i);

        personas.remove(i);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
        List<String[]> listaPersonas = new ArrayList<String[]>();
        if(personas.isEmpty()){
            listaPersonas = null;
        }else{
            for(Integer llave: personas.keySet()){
                listaPersonas.add(personas.get(llave));
            }
        }
        this.controlador.buscarArchivosPorPersonas(listaPersonas);
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        int filaSel = this.jTable1.getSelectedRow();
        ArrayList fila = this.modeloTabla.getRowAt(filaSel);
        String idEtiqueta = (String) fila.get(0);
        try{
            String idContenidoFisico = controlador.calcularHashEtiqueta(idEtiqueta);
            this.etiquetaSeleccionada = idEtiqueta;
            controlador.obtenerInformacionImagen(idContenidoFisico);

        } catch(Exception f){
            f.printStackTrace();
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        this.controlador.removeObserver(this);
        this.dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BuscarContenidoInicio().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList componenteListaPersonas;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jtextApellido;
    private javax.swing.JTextField jtextNombre;
    // End of variables declaration//GEN-END:variables

    public void update(Observable o, Object arg) {
       if(arg instanceof TreeMap){
          TreeMap<String, AdvertisementImagenImpl> mapa = (TreeMap<String, AdvertisementImagenImpl>)  arg;
          
          List<AdvertisementImagenImpl> lista = new ArrayList<AdvertisementImagenImpl>();

          if(mapa == null){
              lista = null;
          } else {
              for(String llave:mapa.keySet()){
                  lista.add(mapa.get(llave));
              }
          }
          

          if(lista != null){
              this.modeloTabla.clear();
              this.results.clear();
              for(AdvertisementImagenImpl img:lista){
                   ArrayList lista2 = new ArrayList();
                   lista2.add(img.getEtiqueta());
                   lista2.add(img.getFechaCreacion());
                   List<String[]> pers = img.getListaPersonas();
                   if(pers==null){
                       lista2.add("");
                   } else {
                       String cadena = "";

                        boolean primero = true;
                        for(String[] per:pers){
                            if(primero){
                                primero = false;
                            } else {
                                cadena += ", ";
                            }
                            cadena += per[0] + " " + per[1];
                        }
                        lista2.add(cadena);
                  }
                  this.modeloTabla.addRow(lista2);
                  this.results.put(img.getEtiqueta(), img);
              }
          }

      }
    else if(arg instanceof AdvertisementContenidoFisicoImpl) {
        AdvertisementContenidoFisicoImpl cont = (AdvertisementContenidoFisicoImpl) arg;
        String nomarch = this.etiquetaSeleccionada;

        if(nomarch!=null){
             try {
                AdvertisementImagenImpl infoImg = this.results.get(nomarch);

                String extension = "";
                String mime = cont.getMimeTypeArchivoFisico();
                if(mime.equals(TiposMime.MIMETYPEPNG)){
                    extension = ".png";
                } else if(mime.equals(TiposMime.MIMETYPEGIF)){
                    extension = ".gif";
                } else if(mime.equals(TiposMime.MIMETYPEJPG)){
                    extension = ".jpg";
                }

                String nombreArchivoImagen = ControladorProySistDistribuidos.rutaCarpetaDescarga + nomarch + extension;

                File archivo = new File(nombreArchivoImagen);
                if(!archivo.exists()){
                    archivo.createNewFile();
                }

                //Se escribe la imagen
                FileOutputStream fos = new FileOutputStream(archivo);

                String contenidoArchivoB64 = cont.getContenidoBase64();
                BASE64Decoder dec = new BASE64Decoder();
                byte[] imagen = dec.decodeBuffer(contenidoArchivoB64);

                fos.write(imagen);
                fos.close();


                File archivoPersonas = new File(ControladorProySistDistribuidos.rutaCarpetaDescarga + nomarch + ".ips");
                if(!archivoPersonas.exists()){
                    archivoPersonas.createNewFile();
                }

                PrintWriter wrt1 = new PrintWriter(archivoPersonas);

                List<String[]> pers = infoImg.getListaPersonas();
                if(pers==null){
                    wrt1.close();
                } else {
                    for(String[] per:pers){
                        wrt1.println(per[0]+";"+per[1]);
                    }
                    wrt1.close();
                 }

                File archivoDetalles = new File(ControladorProySistDistribuidos.rutaCarpetaDescarga + nomarch + ".iim");
                if(!archivoDetalles.exists()){
                    archivoDetalles.createNewFile();
                }

                PrintWriter wrt2 = new PrintWriter(archivoDetalles);
                wrt2.println(infoImg.getEtiqueta());
                wrt2.println(infoImg.getFechaCreacion());
                wrt2.println(AdvertisementImagenImpl.formato.format(new Date()));

                wrt2.close();

                JOptionPane.showMessageDialog(null,"Archivo descargado exitosamente.", "Exito", JOptionPane.INFORMATION_MESSAGE);

            } catch (IOException ex) {
                    Logger.getLogger(BuscarImagenInicio.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
       }
    }

}
